class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> result = new ArrayList<>();
        for(int i=nums.length-1;i>=2;i--){
            if(i<nums.length-1&&nums[i]==nums[i+1]){
                continue;
            }
            if(nums[i]<0){
                break;
            }
            int right=i-1,left=0;
            while(right>left){
                if(nums[right]+nums[left]+nums[i]>0){
                    right--;
                }
                else if(nums[right]+nums[left]+nums[i]<0){
                    left++;
                    if(nums[left]>0) break;
                }
                else{
                    result.add(Arrays.asList(nums[i], nums[left], nums[right]));
                    left++;
                    right--;
                    while(left<right&&nums[left]==nums[left-1]) left++;
                }
            }
        }
        return result;
    }
}